import * as vscode from 'vscode'
import { RecordData } from '../types'
import { DetailPanelRenderer } from '../ui/detailPanel'

export class DetailPanelService {
  private detailPanels = new Map<number, vscode.WebviewPanel>()
  private shouldClearOnStartup: boolean
  private allowMultiplePanels: boolean
  private renderer: DetailPanelRenderer

  constructor(
    private getRecord: (recordId: number) => RecordData | null,
    shouldClearOnStartup: boolean = true,
    allowMultiplePanels: boolean = false
  ) {
    this.shouldClearOnStartup = shouldClearOnStartup
    this.allowMultiplePanels = allowMultiplePanels
    this.renderer = new DetailPanelRenderer()

    console.log('DetailPanelService 初始化完成')
    console.log(`配置 - 启动时清理面板: ${shouldClearOnStartup}`)
    console.log(`配置 - 允许多个面板: ${allowMultiplePanels}`)
  }

  // 显示记录详情
  showRecordDetail(record: RecordData): void {
    // 检查是否已存在该记录的面板
    const existingPanel = this.detailPanels.get(record.id)
    if (existingPanel) {
      console.log(`记录 #${record.id} 的详情面板已存在，聚焦显示`)
      existingPanel.reveal(vscode.ViewColumn.Two)
      return
    }

    // 单开模式：关闭其他所有面板
    if (!this.allowMultiplePanels && this.detailPanels.size > 0) {
      console.log('单开模式：关闭其他详情面板')
      this.closeAllOtherPanels()
    }

    console.log(`创建记录 #${record.id} 的详情面板`)

    const panel = vscode.window.createWebviewPanel('recordDetail', `记录详情 #${record.id}`, vscode.ViewColumn.Two, {
      enableScripts: true,
      retainContextWhenHidden: true
    })

    this.detailPanels.set(record.id, panel)

    // 设置HTML内容
    panel.webview.html = this.renderer.generateHtml(record)

    // 处理来自webview的消息
    panel.webview.onDidReceiveMessage(message => {
      this.handleWebviewMessage(message, record)
    })

    panel.onDidDispose(() => {
      console.log(`记录详情面板 #${record.id} 已销毁`)
      this.detailPanels.delete(record.id)

      // 显示当前打开的面板状态
      console.log(`当前打开的面板数量: ${this.detailPanels.size}`)
      if (this.detailPanels.size > 0) {
        console.log(`剩余面板: [${Array.from(this.detailPanels.keys()).join(', ')}]`)
      }
    })

    // 保存状态用于恢复
    panel.webview.postMessage({
      command: 'setState',
      recordId: record.id
    })

    // 显示当前状态
    console.log(`✅ 面板创建成功，当前打开面板数: ${this.detailPanels.size}`)
    console.log(`当前面板列表: [${Array.from(this.detailPanels.keys()).join(', ')}]`)
  }

  // 处理来自webview的消息
  private handleWebviewMessage(message: any, record: RecordData): void {
    switch (message.command) {
      case 'tagClicked':
        // 处理标签点击事件
        vscode.window.showInformationMessage(`点击了标签: ${message.tag}`)
        // 这里可以扩展为搜索相同标签的记录等功能
        break
      case 'showNotification':
        vscode.window.showInformationMessage(message.message)
        break
      default:
        console.log('未处理的webview消息:', message)
    }
  }

  // 关闭除指定记录外的所有面板
  private closeAllOtherPanels(exceptRecordId?: number): void {
    console.log(`关闭除记录 #${exceptRecordId} 外的所有面板...`)

    const toClose: number[] = []
    this.detailPanels.forEach((panel, recordId) => {
      if (recordId !== exceptRecordId) {
        toClose.push(recordId)
        panel.dispose()
      }
    })

    toClose.forEach(recordId => {
      this.detailPanels.delete(recordId)
      console.log(`已关闭记录详情面板 #${recordId}`)
    })

    if (toClose.length > 0) {
      console.log(`✅ 已关闭 ${toClose.length} 个面板`)
    }
  }

  // 关闭指定记录的详情面板
  closeRecordDetailPanel(recordId: number): void {
    const panel = this.detailPanels.get(recordId)
    if (panel) {
      console.log(`手动关闭记录详情面板 #${recordId}`)
      panel.dispose()
      this.detailPanels.delete(recordId)
    }
  }

  // 关闭所有详情面板
  closeAllDetailPanels(): void {
    console.log('正在关闭所有详情面板...')

    const panelCount = this.detailPanels.size

    // 遍历并关闭所有面板
    this.detailPanels.forEach((panel, recordId) => {
      try {
        panel.dispose()
        console.log(`已关闭记录详情面板 #${recordId}`)
      } catch (error) {
        console.error(`关闭面板 #${recordId} 时出错:`, error)
      }
    })

    // 清空面板映射
    this.detailPanels.clear()

    if (panelCount > 0) {
      console.log(`✅ 已清理 ${panelCount} 个详情面板`)
    }
  }

  // 获取当前打开的面板数量
  getOpenPanelsCount(): number {
    return this.detailPanels.size
  }

  // 获取所有打开的面板ID
  getOpenPanelIds(): number[] {
    return Array.from(this.detailPanels.keys())
  }

  // 获取面板模式信息
  getPanelModeInfo(): { allowMultiple: boolean; currentCount: number; panelIds: number[] } {
    return {
      allowMultiple: this.allowMultiplePanels,
      currentCount: this.detailPanels.size,
      panelIds: this.getOpenPanelIds()
    }
  }

  // 动态更新配置（可选）
  updateConfig(allowMultiplePanels: boolean): void {
    const wasMultiple = this.allowMultiplePanels
    this.allowMultiplePanels = allowMultiplePanels

    console.log(`面板模式已更新: ${wasMultiple ? '多开' : '单开'} → ${allowMultiplePanels ? '多开' : '单开'}`)

    // 如果从多开切换到单开，且当前有多个面板，只保留最新的
    if (wasMultiple && !allowMultiplePanels && this.detailPanels.size > 1) {
      console.log('切换到单开模式，关闭多余面板')

      // 获取最后打开的面板（通过Map的插入顺序）
      const panelIds = Array.from(this.detailPanels.keys())
      const latestPanelId = panelIds[panelIds.length - 1]

      // 关闭除最新面板外的所有面板
      this.closeAllOtherPanels(latestPanelId)
    }
  }

  // 反序列化详情面板 - 根据初始化时的配置决定是否恢复
  deserializeDetailPanel(webviewPanel: vscode.WebviewPanel, state: any): void {
    console.log('处理详情面板恢复，配置清理模式:', this.shouldClearOnStartup)

    if (this.shouldClearOnStartup) {
      // 配置为清理面板：销毁面板
      console.log('销毁之前的详情面板（清理模式）')
      webviewPanel.dispose()

      if (state && state.recordId) {
        console.log(`已销毁记录 #${state.recordId} 的详情面板`)
      }
      return
    }

    // 配置为保留面板：尝试恢复
    console.log('尝试恢复详情面板（保留模式）')

    if (state && state.recordId) {
      const record = this.getRecord(state.recordId)

      if (record) {
        // 单开模式且已有面板：关闭其他面板
        if (!this.allowMultiplePanels && this.detailPanels.size > 0) {
          console.log('单开模式恢复：关闭其他面板')
          this.closeAllOtherPanels()
        }

        // 恢复面板内容
        webviewPanel.webview.html = this.renderer.generateHtml(record)
        this.detailPanels.set(record.id, webviewPanel)

        // 重新绑定销毁事件
        webviewPanel.onDidDispose(() => {
          console.log(`恢复的记录详情面板 #${record.id} 已销毁`)
          this.detailPanels.delete(record.id)
        })

        // 恢复面板标题
        webviewPanel.title = `记录详情 #${record.id}`

        console.log(`✅ 成功恢复记录详情面板 #${record.id}`)
      } else {
        // 如果找不到记录，销毁面板
        console.log(`❌ 记录 #${state.recordId} 不存在，销毁面板`)
        webviewPanel.dispose()
      }
    } else {
      // 没有有效状态，销毁面板
      console.log('❌ 没有有效状态，销毁面板')
      webviewPanel.dispose()
    }
  }
}
